package server;

import handler.PipelineHandler;
import handler.server.SwordHeartBeatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;
import utils.SendUtils;

public class SwordServe {

	// 存有每一个通道
	public static final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

	public static void run(int port,PipelineHandler handler){

		try(EventLoopGroup bossGroup = new NioEventLoopGroup();
			EventLoopGroup workerGroup = new NioEventLoopGroup()) {
			// 核心引导类
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) {
							channelGroup.add(socketChannel);
							ChannelPipeline pipeline = socketChannel.pipeline();
							pipeline.addLast(new SwordHeartBeatHandler());
							handler.handle(pipeline);
						}
					});

			ChannelFuture future = bootstrap.bind(port).sync();

			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}
}
